using System.Collections.ObjectModel;
using QueryBuilder.Core.Common;

namespace QueryBuilder.Core.Visualization.QueryVisualization
{
    public abstract class VisualizableConstraint : ViewModel
    {
        private readonly FreezableObservableCollection<VisualizableConstraint> constraints
            = new FreezableObservableCollection<VisualizableConstraint>();

        private readonly object sync = new object();

        protected VisualizableConstraint()
        {
            this.constraints.IsFrozan = true;
        }

        /// <summary>
        /// Gets the constraints.
        /// </summary>
        /// <value>The constraints.</value>
        public ObservableCollection<VisualizableConstraint> Constraints
        {
            get { return this.constraints; }
        }

        public VisualizableConstraint Parent { get; set; }

        public abstract void Accept(IVisualizableConstraintVisitor visitor);

        public virtual void RemoveChild(VisualizableConstraint visualizableConstraint)
        {
            lock (this.sync)
            {
                this.constraints.IsFrozan = false;
                this.Constraints.Remove(visualizableConstraint);
                visualizableConstraint.Parent = null;
                this.constraints.IsFrozan = true;
            }
        }

        public virtual void AddChild(VisualizableConstraint visualizableConstraint)
        {
            lock (this.sync)
            {
                this.constraints.IsFrozan = false;
                VisualizableConstraint parent = visualizableConstraint.Parent;
                if (parent != null)
                {
                    parent.Constraints.Remove(visualizableConstraint);
                }
                this.Constraints.Add(visualizableConstraint);
                visualizableConstraint.Parent = this;
                this.constraints.IsFrozan = true;
            }
        }
    }
}